'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
    // 添加order_no字段到sales_orders表
    await queryInterface.addColumn('sales_orders', 'order_no', {
      type: Sequelize.STRING(50),
      allowNull: true,  // 先允许为空
      comment: '订单编号'
    });

    // 添加索引
    await queryInterface.addIndex('sales_orders', ['order_no']);

    // 为现有记录生成订单编号
    await queryInterface.sequelize.query(`
      UPDATE sales_orders 
      SET order_no = CONCAT('SO', DATE_FORMAT(order_date, '%Y%m%d'), LPAD(id, 4, '0'))
      WHERE order_no IS NULL
    `);

    // 修改字段为不允许为空
    await queryInterface.changeColumn('sales_orders', 'order_no', {
      type: Sequelize.STRING(50),
      allowNull: false,
      unique: true,
      comment: '订单编号'
    });
  },

  async down (queryInterface, Sequelize) {
    // 回滚：删除order_no字段
    await queryInterface.removeColumn('sales_orders', 'order_no');
  }
};